package com.atguigu.web;

import com.atguigu.dao.UserDao;
import com.atguigu.dao.impl.UserDaoImpl;
import com.atguigu.pojo.User;
import com.atguigu.service.UserService;
import com.atguigu.service.impl.UserServiceImpl;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;

@WebServlet(name = "RegisteServlet", value = "/RegisteServlet")
public class RegisteServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

//     1.获取请求的参数
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String email = req.getParameter("email");
        String code = req.getParameter("code");

//        2.检查验证码是否正确
        if ("abcd".equalsIgnoreCase(code)) {
//        正确

            //        3.检查用户名是否可用
            if (userService.existUsername(username)) {

                req.setAttribute("msg","用户名已存在");
                req.setAttribute("username",username);
                System.out.println("用户名" + username + "已存在");

//        跳回注册页面
                req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);

            } else {

                //        可用
                //        调用service保存数据库
                userService.registUser(new User(null, username, password, email));

                //          返回regist_success.html页面
                req.getRequestDispatcher("/pages/user/regist_success.jsp").forward(req,resp);
            }


            //        不正确
        } else {

            req.setAttribute("msg","验证码不正确");
            System.out.println("验证码" +code+"不正确");

            //        跳回register.html页面
            req.getRequestDispatcher("/pages/user/regist.jsp").forward(req,resp);
        }


    }
}
